import random
import re

from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status as http_status

from edu_django.libs.geetest import GeetestLib
from edu_django.utils import contastnt
from edu_django.utils.contastnt import PC_GEETEST_ID, PC_GEETEST_KEY
from edu_django.utils.send_msg import Message
from user.models import User
from user.serializer import UserModelSerializer, PhoneLoginModelSerializer
from user.utils import get_user_by_account

pc_geetest_id = PC_GEETEST_ID
pc_geetest_key = PC_GEETEST_KEY


class CaptchaAPIView(APIView):
    user_id = 0
    status = False

    def get(self, request, *args, **kwargs):
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        self.status = gt.pre_process(self.user_id)
        response_str = gt.get_response_str()
        return Response(response_str)

    def post(self, request, *args, **kwargs):
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        if self.user_id:
            result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)


class UserAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class MobileCheckAPIView(APIView):

    def get(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        if not re.match(r"^1[35678]\d{9}$", phone):
            return Response({'message': '手机号不合法'}, status=http_status.HTTP_400_BAD_REQUEST)
        user = get_user_by_account(phone)

        if user is not None:
            return Response({'message': '该手机号已被注册'}, status=http_status.HTTP_400_BAD_REQUEST)
        return Response({'message': 'OK'})


class SendMessageAPIView(APIView):

    def get(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        redis_connection = get_redis_connection('sms_code')
        mobile_code = redis_connection.get('sms_%s' % phone)

        if not re.match(r"^1[35678]\d{9}$", phone):
            return Response({'message': '手机号不合法'}, status=http_status.HTTP_400_BAD_REQUEST)

        if mobile_code is not None:
            return Response({'message': '您已在60s内发过短信了，请注意查收'}, status=http_status.HTTP_400_BAD_REQUEST)

        code = "%06d" % random.randint(0, 999999)

        redis_connection.setex("sms_%s" % phone, contastnt.SMS_EXPIRE_TIME, code)
        redis_connection.setex("mobile_%s" % phone, contastnt.CODE_EXPIRE_TIME, code)

        try:
            message = Message(contastnt.API_KEY)
            message.send_message(phone, code)
        except:
            return Response({'message': '短信发送失败，请检查手机号'}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({'message': '短信发送成功'}, status=http_status.HTTP_200_OK)


class PhoneLoginAPIView(APIView):
    permission_classes = ()
    authentication_classes = ()

    def post(self, request, *args, **kwargs):
        serializer = PhoneLoginModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = {
            'token': serializer.token,
            'user': PhoneLoginModelSerializer(serializer.obj).data,
        }
        return Response(data)